package cn.com.cloudpioneer.evaluate.utils;

import cn.com.cloudpioneer.evaluate.model.UserModel;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.*;

/**
 * @auther maruikai
 * @create 2023/9/25-9:08
 */
public class JwtUtils {

    //创建Token
    public static String createJwt(UserModel userModel) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        String token = JWT.create()
                .withIssuedAt(new Date())
                .withHeader(map) //设置头信息
                .withClaim("userId", userModel.getUserId()) //设置payload 携带信息
                .sign(Algorithm.HMAC256(Values.SECRET)); //设置签名以及签名方式 这里使用HMAC256加密方式

        return token;
    }

    public static String getUserId(final String token) throws CustomException {
        DecodedJWT verify = null;
        try {
            //创建检验对象
            JWTVerifier require = JWT.require(Algorithm.HMAC256(Values.SECRET)).build();
            //通过签名进行解析token
            verify = require.verify(token);
        } catch (Exception e) {
           throw new CustomException(401,"登录超时");
        }
        //通过verify的方法可以拿到之前装载的数据
        return verify.getClaim("userId").asString();
    }
}

